package service

import (
	"context"
	"errors"
	"time"

	"goserver/internal/model"
)

type RobotCodeService struct {
	robotCodeModel *model.RobotCodeModel
}

func NewRobotCodeService(robotCodeModel *model.RobotCodeModel) *RobotCodeService {
	return &RobotCodeService{
		robotCodeModel: robotCodeModel,
	}
}

// CreateRobotCodes 批量创建机器码
func (s *RobotCodeService) CreateRobotCodes(ctx context.Context, userID int, count int, expireDays int) ([]*model.RobotCode, error) {
	if count <= 0 || count > 100 {
		return nil, errors.New("无效的机器码数量")
	}

	expireTime := time.Now().AddDate(0, 0, expireDays)
	var codes []*model.RobotCode

	for i := 0; i < count; i++ {
		code := &model.RobotCode{
			UserID:     userID,
			RobotID:    s.robotCodeModel.GenerateRobotID(),
			Status:     1,
			ExpireTime: expireTime,
		}

		if err := s.robotCodeModel.CreateRobotCode(ctx, code); err != nil {
			continue
		}

		codes = append(codes, code)
	}

	if len(codes) == 0 {
		return nil, errors.New("机器码创建失败")
	}

	return codes, nil
}

// GetUserRobotCodes 获取用户的机器码列表
func (s *RobotCodeService) GetUserRobotCodes(ctx context.Context, userID int) ([]*model.RobotCode, error) {
	return s.robotCodeModel.GetRobotCodes(ctx, userID)
}

// ValidateRobotCode 验证机器码
func (s *RobotCodeService) ValidateRobotCode(ctx context.Context, robotID string) (*model.RobotCode, error) {
	code, err := s.robotCodeModel.GetRobotCode(ctx, robotID)
	if err != nil {
		return nil, errors.New("机器码不存在")
	}

	if code.Status != 1 {
		return nil, errors.New("机器码已禁用")
	}

	if !code.ExpireTime.IsZero() && time.Now().After(code.ExpireTime) {
		return nil, errors.New("机器码已过期")
	}

	return code, nil
}

// UpdateRobotCode 更新机器码状态
func (s *RobotCodeService) UpdateRobotCode(ctx context.Context, code *model.RobotCode) error {
	return s.robotCodeModel.UpdateRobotCode(ctx, code)
}

// DeleteRobotCode 删除机器码
func (s *RobotCodeService) DeleteRobotCode(ctx context.Context, userID, codeID int) error {
	// 验证机器码属于该用户
	codes, err := s.robotCodeModel.GetRobotCodes(ctx, userID)
	if err != nil {
		return err
	}

	for _, code := range codes {
		if code.ID == codeID {
			return s.robotCodeModel.DeleteRobotCode(ctx, codeID)
		}
	}

	return errors.New("无权操作此机器码")
} 